 let teachersMap = {};
document.addEventListener('DOMContentLoaded', () => {
    // DOM元素
    const modal = document.getElementById('modal');
    const modalContent = document.getElementById('modalContent');
    const modalForm = document.getElementById('courseForm');
    const modalTitle = document.getElementById('modalTitle');
    const saveBtn = document.getElementById('saveButton');
    const closeModalBtn = document.getElementById('close-model');
    const cancelBtn = document.getElementById('cancelButton');
    const addCourseBtns = document.querySelectorAll('#addCourseBtn, .empty-state-add-btn');
    const courseTableBody = document.getElementById('courseTableBody');


    // 状态变量
    let currentMode = 'add'; // 'add' 或 'edit'
    let currentCourseId = null;

    // 初始化事件监听
    function initEventListeners() {
        // 新增课程按钮
        addCourseBtns.forEach(btn => {
            btn.addEventListener('click', () => openModal('add'));
        });
        loadTeachers();
        bindTeacherChangeEvent();
        // 编辑/删除按钮（使用事件委托）
        if (courseTableBody) {
            courseTableBody.addEventListener('click', (e) => {
                const target = e.target.closest('.edit-btn, .delete-btn');
                if (!target) return;

                const courseRow = target.closest('tr');
                const courseId = courseRow?.dataset?.courseId;

                if (!courseId) return;

                if (target.classList.contains('edit-btn')) {
                    openModal('edit', courseId);
                } else if (target.classList.contains('delete-btn')) {
                    deleteCourse(courseId);
                }
            });
        }

        // 模态框按钮
        if (saveBtn) saveBtn.addEventListener('click', saveCourse);
        if (closeModalBtn) closeModalBtn.addEventListener('click', closeModal);
        if (cancelBtn) cancelBtn.addEventListener('click', closeModal);
    }

    // 打开模态框
    function openModal(mode, id = null) {
        currentMode = mode;
        currentCourseId = id;

        // 重置表单
        if (modalForm) modalForm.reset();

        // 设置模态框标题和按钮文本
        if (mode === 'add') {
            modalTitle.textContent = '新增课程';
            if (saveBtn) saveBtn.innerHTML = '<i class="fa fa-plus mr-1"></i> 新增';
            if (modalForm) document.getElementById('courseId').value = '';

        } else if (mode === 'edit') {
            modalTitle.textContent = '编辑课程';
            if (saveBtn) saveBtn.innerHTML = '<i class="fa fa-check mr-1"></i> 更新';
            // 填充表单数据

            populateFormData(id);

        }

        // 显示模态框
        if (modal) modal.classList.remove('opacity-0', 'pointer-events-none');
        if (modalContent) {
            setTimeout(() => {
                modalContent.classList.remove('scale-95');
                modalContent.classList.add('scale-100');
            }, 10);
        }

        // 阻止背景滚动
        document.body.style.overflow = 'hidden';
    }

    // 通过API加载教师数据
    async function loadTeachers() {

        try {
            const response = await fetch('/admin/course/get_teachers');
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            if (data.success && data.teachers) {
                // 构建教师映射
                data.teachers.forEach(teacher => {
                    teachersMap[teacher.id] = {
                        name: teacher.username,
                        department: teacher.department
                    };
                });

                // 填充教师选择下拉框
                populateTeacherSelect(data.teachers);
            }
        } catch (error) {
            console.error('加载教师数据失败:', error);
            showToast('加载教师数据失败，请重试', 'error');
        }
    }

    // 填充教师选择下拉框
    function populateTeacherSelect(teachers) {
            const teacherSelect = document.getElementById('teacherId');
            const departmentInput = document.getElementById('department');

        if (!teacherSelect) return;

        // 清空现有选项
        teacherSelect.innerHTML = '<option value="">请选择教师</option>';

        // 添加教师选项
        teachers.forEach(teacher => {
            const option = document.createElement('option');
            option.value = teacher.id;
            option.textContent = `${teacher.username} (${teacher.department})`;
            teacherSelect.appendChild(option);
        });
    }

// 监听教师选择变化，自动填充院系
    function bindTeacherChangeEvent() {
          const teacherSelect = document.getElementById('teacherId');
            const departmentInput = document.getElementById('department');
        if (!teacherSelect || !departmentInput) return;

        teacherSelect.addEventListener('change', (e) => {
            const teacherId = e.target.value;
            if (teacherId) {
                // 从映射中获取院系并填充
                departmentInput.value = teachersMap[teacherId].department;
            } else {
                // 未选择教师时清空院系
                departmentInput.value = '';
            }
        });
    }



    // 关闭模态框
    function closeModal() {
        if (modalContent) modalContent.classList.remove('scale-100');
        if (modalContent) modalContent.classList.add('scale-95');

        if (modal) {
            setTimeout(() => {
                modal.classList.add('opacity-0', 'pointer-events-none');
                document.body.style.overflow = '';
            }, 300);
        }
    }

    // 填充表单数据（编辑模式）
    async function populateFormData(id) {
        try {
            // 向后端发送请求获取课程详情
            const response = await fetch(`/admin/course/get-course/${id}`);
            if (!response.ok) throw new Error('获取课程信息失败');
            const course = await response.json();
            if (!course.success) throw new Error(course.message);

            // 填充表单数据
            if (modalForm) {
                document.getElementById('courseId').value = course.data.id;
                document.getElementById('courseCode').value = course.data.course_code;
                document.getElementById('courseName').value = course.data.course_name;
                document.getElementById('department').value = course.data.department;
                document.getElementById('teacherId').value = course.data.teacher_id;
                document.getElementById('credit').value = course.data.credit;
                document.getElementById('courseType').value = course.data.course_type;
                document.getElementById('location').value = course.data.location;

                // 处理日期格式
                const date = new Date(course.data.time);
                document.getElementById('time').value = date.toISOString().slice(0, 16);

                document.getElementById('description').value = course.data.description || '';

                // 触发教师选择事件，自动填充院系（可选）
                const teacherSelect = document.getElementById('teacherId');
                teacherSelect.value = course.data.teacher_id;
                teacherSelect.dispatchEvent(new Event('change'));
            }
        } catch (error) {
            console.error('编辑模式数据加载失败:', error);
            showToast('加载课程信息失败，请重试', 'error');
            closeModal(); // 加载失败时关闭模态框
        }
    }


    // 保存课程（新增或编辑）
    async function saveCourse() {
        if (!modalForm) return;

        const formData = new FormData(modalForm);

        // 表单验证
        const requiredFields = ['courseCode', 'courseName', 'department', 'teacherId', 'credit', 'courseType', 'location', 'time'];
        for (const field of requiredFields) {
            if (!formData.get(field)) {
                showToast('请填写所有必填字段', 'error');
                return;
            }
        }

        try {
            const isEdit = currentMode === 'edit';
            const url = isEdit
                ? `/admin/course/update-course/${currentCourseId}`
                : '/admin/course/add_course';
            const method = isEdit ? 'PUT' : 'POST';
            // alert(formData.get('courseCode'));
            const response = await fetch(url, {
                method,
                body: formData
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            if (result.success) {
                showToast(isEdit ? '课程更新成功' : '课程创建成功', 'success');
                closeModal();

                // 刷新页面或更新表格
                if (isEdit) {
                           window.location.reload();
                }
            } else {
                showToast(result.message || '操作失败', 'error');
            }
        } catch (error) {
            showToast('网络错误，请重试', 'error');
            console.error('保存课程失败:', error);
        }
    }



    // 删除课程
    async function deleteCourse(id) {
        if (!confirm('确定要删除该课程吗？此操作不可撤销。')) {
            return;
        }

        try {
            const response = await fetch(`/admin/course/delete_course/${id}`, {
                method: 'DELETE'
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            if (result.success) {
                showToast('课程已删除', 'success');

                // 从表格中移除行
                const row = document.querySelector(`tr[data-course-id="${id}"]`);
                if (row) {
                    row.classList.add('opacity-0');
                    setTimeout(() => row.remove(), 300);

                    // 如果表格为空，显示空状态
                    if (document.querySelectorAll('tbody tr').length === 1) {
                        setTimeout(() => window.location.reload(), 500);
                    }
                }
            } else {
                showToast(result.message || '删除失败', 'error');
            }
        } catch (error) {
            showToast('网络错误，请重试', 'error');
            console.error('删除课程失败:', error);
        }
    }



    // 显示提示消息
    function showToast(message, type = 'success') {
        const toast = document.createElement('div');
        toast.className = `fixed top-4 right-4 px-4 py-2 rounded-md shadow-lg text-white z-50 ${
            type === 'success' ? 'bg-green-500' : 'bg-red-500'
        }`;
        toast.textContent = message;
        document.body.appendChild(toast);

        // 3秒后自动消失
        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateY(20px)';
            toast.style.transition = 'opacity 300ms, transform 300ms';
            setTimeout(() => document.body.removeChild(toast), 300);
        }, 3000);
    }

    // 初始化
    initEventListeners();
});